<?php


namespace app\api\controller;

use app\BaseController;
use app\model\CouponOrderSid;
use think\facade\Cache;
use think\Request;
use app\api\validate\JdCallCharges as JxCallChargesValidate;
use api\channel\JdUnion\PromotionBysubunionidGet;

class JdCallCharges extends BaseController
{
    protected $middleware = [
        \app\middleware\ApiChannel::class,
        \app\middleware\ApiUserAuthV2::class => ['except' => ['phoneInfo']],
    ];

    protected function initialize()
    {
        parent::initialize();

    }

    /**
     * Notes:社交媒体获取推广链接
     * User: ymzhang
     * Date: 2022/08/02
     * Time: 13:40
     * @return \think\response\Json
     */
    public function turnChain(Request $request, JxCallChargesValidate $validate)
    {
        $data = $request->param();
        $validate->scene('turn_chain');
        if (!$validate->scene('turn_chain')->check($data)) {
            return fail($validate->getError());
        }
        $sid = (new CouponOrderSid())->generateNew(PRODUCT_MOBILE_CPS_SERV, CouponOrderSid::REMARK_JX);
        $cache_key = $sid.$data['skuId'];
        $result =  Cache::get($cache_key);
        if ($result) {
            return success('转链成功', $result);
        }
        $handler = new PromotionBysubunionidGet();
        $params = [
            'materialId' => 'https://item.jd.com/'.$data['skuId'].'.html',
            'chainType'  => 3,
        ];
        if (isset($data['couponUrl']) && !empty($data['couponUrl'])) {
            $params['couponUrl'] = trim($data['couponUrl']);
        }

        if ($sid) {
            $params['subUnionId'] = (string)$sid;
        }

        $result = $handler->jd_union_open_promotion_bysubunionid_get($params);
        if (!$result['status'] && empty($result['data'])) {
            return fail('转链失败');
        }
        //组装数据集
        $res = array();
        //判断是否需要跳转小程序
        if (isset($data['isJumpApplets']) && $data['isJumpApplets']) {
            $res['wechatApp']['id']    = 'gh_d227644b6f7c';
            $res['wechatApp']['appId'] = 'wxca1fe42a16552094';
            //$res['wechatApp']['path']  = '/pages/union/proxy/proxy?spreadUrl='.urlencode($result['data']['clickURL']).'&customerinfo=20191009DMHW';
            $res['wechatApp']['path']  = '/pages/union/proxy/proxy?spreadUrl='.urlencode($result['data']['shortURL']).'&customerinfo=20191009DMHW';
        }
        $res['longURL'] = $result['data']['clickURL'];
        $res['shortURL'] = $result['data']['shortURL'];
        Cache::set($cache_key, $res, 30*24*3600);
        return success('转链成功', $res);
    }
}